<script lang="ts" setup>
	import TnTitle from '@/uni_modules/tuniaoui-vue3/components/title/src/title.vue'
	import TnListItem from '@/uni_modules/tuniaoui-vue3/components/list/src/list-item.vue'
	import TnInput from '@/uni_modules/tuniaoui-vue3/components/input/src/input.vue'
	import TnButton from '@/uni_modules/tuniaoui-vue3/components/button/src/button.vue'
	import TnPopup from '@/uni_modules/tuniaoui-vue3/components/popup/src/popup.vue'
	import TnPicker from '@/uni_modules/tuniaoui-vue3/components/picker/src/picker.vue'
	import TnCircleProgress from '@/uni_modules/tuniaoui-vue3/components/circle-progress/src/circle-progress.vue'
	import type { TnActionSheetInstance, TnCountDownInstance } from '@/uni_modules/tuniaoui-vue3'
	import TnCountDown from '@/uni_modules/tuniaoui-vue3/components/count-down/src/count-down.vue'


	import { onLoad } from '@dcloudio/uni-app'
	import { reactive, ref } from 'vue';
	import { getContentInfo, getContentList, getContentTypeList, saveContent } from '../../utils/content'
	import { ContentListSchema, ContentSchema, ContentTypeSchema, FileSchema, Response } from '../../utils/schema'
	import { OK } from '../../utils/constant'
	import { uploadFile } from '../../utils/api'
	import { BASE_URL } from '../../utils/env'

	export interface recorderManagerSchema {
		tempFilePath : string,
		duration : number,
		fileSize : number,
	}

	const innerAudio = uni.createInnerAudioContext()
	innerAudio.onCanplay(() => {
		setTimeout(() => {
			voiceCountDown.duration = innerAudio.duration;
			console.log('onCanplay：音频时长加载完毕=', voiceCountDown.duration);
		}, 1000);
	})
	const recorderManager = uni.getRecorderManager();
	const contentPopupTitle = ref('')
	const typePicker = ref(false)
	const actionSheetRef = ref<TnActionSheetInstance>()
	const countDownRef = ref<TnCountDownInstance>()
	const showCreateContentPopup = ref(false)
	const secret_id = ref(0)
	const data = reactive({
		list: {} as ContentListSchema,
		typeList: [] as ContentTypeSchema[],
		timeline: null,
		percent: 0,
		voiceObject: {} as recorderManagerSchema,
	});
	const form = reactive({
		id: 0,
		type_str: '',
		title: '',
		content: '',
		type: 0,
	})
	const showContent = reactive({
		type: 0,
		content: '',
		visible: false
	});
	const voiceCountDown = reactive({
		duration: 0
	})


	const openTypePicker = () => {
		typePicker.value = !typePicker.value
	}


	onLoad(async (option) => {
		if (!option.id) {
			uni.navigateBack()
		}
		secret_id.value = option.id

		getContentTypeList().then((res) => {
			data.typeList = res.data
		})

		getList()
	})

	const getTypeLabel = (type_id : number) => {
		return data.typeList.find(item => item.value === type_id).label
	}

	const getList = async () => {
		const content : Response<ContentListSchema> = await getContentList(secret_id.value);
		data.list = content.data
	}


	/**
	 * type : 1 新增 2 修改
	 */
	const clickContentPopup = (type : number) => {
		showCreateContentPopup.value = !showCreateContentPopup.value
		switch (type) {
			case 1:
				contentPopupTitle.value = '新增内容'
				form.id = 0
				form.content = ''
				form.title = ''
				form.type = 0
				form.type_str = ''
				break;
			case 2:
				contentPopupTitle.value = '修改内容'
				break;
		}
	}

	const clickCreateContent = async () => {
		if (form.type === 1) {
			const file = await uploadFile<FileSchema>(data.voiceObject.tempFilePath);
			if (file.code !== OK) {
				uni.showModal({
					title: file.msg
				});
				return
			}
			form.content = file.data.path
		}

		saveContent({
			secret_id: secret_id.value,
			...form
		}).then((res) => {
			if (res.code !== OK) {
				uni.showModal({
					title: res.msg
				});
				return
			}

			showCreateContentPopup.value = !showCreateContentPopup.value
			getList()
		})
	}

	const openActionSheet = (id : number) => {
		actionSheetRef.value?.show({
			actions: [
				{ text: '查看', value: 1 },
				{ text: '编辑', value: 2 },
			],
			select: async (index : number, value ?: string | number) => {
				const info = await getContentInfo(id)
				if (info.code !== OK) {
					uni.showModal({
						title: info.msg
					});
					return
				}

				switch (value) {
					case 1:
						getContent(info.data)
						break;
					case 2:
						form.id = info.data.id
						form.content = info.data.content
						form.title = info.data.title
						form.type = info.data.type
						form.type_str = getTypeLabel(form.type)
						clickContentPopup(2)
						break;
				}
				return true;
			}
		})
	}

	const getContent = (info : ContentSchema) => {

		if (info.type !== 0) {
			showContent.content = BASE_URL + info.content

			if (info.type === 1) {
				innerAudio.src = showContent.content
				innerAudio.autoplay = false
			}

		} else {
			showContent.content = info.content
		}

		showContent.type = info.type
		showContent.visible = true
	}

	const longPressTape = () => {
		uni.authorize({
			scope: 'scope.record',
			success: () => {
				recorderManager.start({});

				data.timeline = setInterval(() => {
					data.percent = data.percent + 2
				}, 1000)
			}
		})
	}
	const touchendTape = () => {
		clearInterval(data.timeline)
		recorderManager.stop();

		recorderManager.onStop((res) => {
			data.voiceObject = res
		})
	}

	const startVoice = () => {
		innerAudio.play()
		countDownRef.value?.start()
	}

	const stopVoice = () => {
		innerAudio.pause()
		countDownRef.value?.stop()
	}

	const resetVoice = () => {
		innerAudio.stop()
		countDownRef.value?.reset()
	}
</script>

<template>
	<view class="tn-p-lg">
		<TnTitle mode="hLine" title="内容列表" color="tn-type-primary" size="32rpx" />
		<view style="height: 40rpx;"></view>


		<TnListItem bottom-border right-icon="right" bg-color="tn-gray-disabled" v-for="item in data.list.list"
			@click="openActionSheet(item.id)">
			<template #default>
				<view style="position: absolute; right: 70rpx;">{{ getTypeLabel(item.type) }}</view>
			</template>
			{{ item.title }}
		</TnListItem>
	</view>


	<view class="fab">
		<TnButton type="primary" shape="circle" size="xl" icon="add" @click="clickContentPopup(1)"></TnButton>
	</view>
	<TnPopup v-model="showCreateContentPopup" open-direction="bottom">
		<view class="tn-p-lg">
			<TnTitle align="center" :title="contentPopupTitle" color="tn-type-primary" size="xl"
				style="text-align: center;" />
			<view style="height: 40rpx;"></view>
			<TnInput v-model="form.title" type="text" placeholder="请输入标题"></TnInput>
			<view style="height: 40rpx;"></view>
			<TnInput v-model="form.type_str" type="select" placeholder="请选择类型" @click="openTypePicker"></TnInput>
			<view style="height: 40rpx;"></view>
			<TnInput v-if="form.type === 0" v-model="form.content" type="textarea" placeholder="请输入内容" height="150">
			</TnInput>
			<view v-if="form.type === 1" class="">
				<view>
					<view class="tn-text-lg tn-text-center" style="margin-bottom: 30rpx;">长按录制语音</view>
					<view class="tn-flex-center-center" @longpress="longPressTape" @touchend="touchendTape">
						<TnCircleProgress :percent="data.percent" style="">
							<template #default>
								<tn-icon name="voice" size="60rpx"></tn-icon>
							</template>
						</TnCircleProgress>
					</view>
				</view>

			</view>
			<view style="height: 40rpx;"></view>
			<TnButton type="primary" width="100%" height="80rpx" size="lg" @click="clickCreateContent">确认</TnButton>
		</view>
	</TnPopup>
	<tn-action-sheet ref="actionSheetRef"></tn-action-sheet>

	<TnPopup v-if="showContent.type===0" v-model="showContent.visible" close-btn width="80%" height="400">
		<view class="tn-p-lg">
			<TnInput v-model="showContent.content" type="textarea" disabled height="150"></TnInput>
		</view>
	</TnPopup>
	<TnPopup v-if="showContent.type===1" v-model="showContent.visible" close-btn width="80%" height="400">
		<view class="tn-p-lg">
			<view class="count-down-item tn-flex-center" style="margin: 70rpx 0rpx;">
				<TnCountDown size="xl" ref="countDownRef" :time="voiceCountDown.duration" :show-hour="false"
					:auto-start="false" />
			</view>
			<view class="count-down-item tn-flex-center">
				<view class="operation-btn">
					<TnButton size="lg" @click="startVoice">播放</TnButton>
				</view>
				<view class="operation-btn">
					<TnButton type="warning" size="lg" @click="stopVoice">
						暂停
					</TnButton>
				</view>
				<view class="operation-btn">
					<TnButton type="danger" size="lg" @click="resetVoice">
						重置
					</TnButton>
				</view>
			</view>
		</view>
	</TnPopup>
	<TnPicker v-model="form.type" v-model:open="typePicker" :data="data.typeList" @confirm="(value: number) => {
		form.type_str = getTypeLabel(value)
	}" />


</template>
<style lang="scss" scoped>
	.fab {
		position: fixed;
		bottom: 100rpx;
		right: 30rpx;
	}

	.count-down-item {
		width: 100%;
		position: relative;

		.operation-btn {
			margin-right: 20rpx;
		}
	}
</style>